# coding: utf-8
#
# 关闭程序的时候需要杀掉所有python进程
#
import multiprocessing
import os
import random
import threading
import time


class Producer(threading.Thread):
    """
    生产任务线程
    """

    def __init__(self, queue):
        self.queue = queue
        super().__init__()

    def run(self):
        print('启动生产线程')
        while True:
            # 产生任务的代码写这里，任务写入队列
            task = str(random.randint(1000, 9999))
            print('生产数字:' + task)
            self.queue.put(task)

            time.sleep(10)


def worker(i, queue):
    """
    处理任务进程
    :param i: 进程序号
    :param queue: 任务队列
    :return:
    """
    print('启动工作进程序号-%s, 进程ID-%s' % (i, os.getpid()))
    while True:
        # 取任务进行处理的代码写这里
        task = queue.get()
        print('消费数字:' + task)


if __name__ == '__main__':
    # 修改CPU的数量提升并行度
    print('主进程启动')
    CPU_CORES = 10
    queue = multiprocessing.Queue()
    producer = Producer(queue)
    producer.start()

    process_list = []

    for i in range(0, CPU_CORES):
        w = multiprocessing.Process(target=worker, args=(i, queue,))
        process_list.append(w)

    for w in process_list:
        w.start()

    for w in process_list:
        w.join()

    producer.join()
